package postgres

import (
	"database/sql"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"lht-go-plugins/LhtLog"
	"lht-go-plugins/LhtSettings"
	"lht-go-plugins/internal/core"
	"strconv"

	_ "github.com/lib/pq"
)

type PostgresPlugin struct {
	*core.BasePlugin
	conf LhtSettings.PostgresConfig
	db   *sql.DB
}

func NewPostgresPlugin() *PostgresPlugin {
	return &PostgresPlugin{
		BasePlugin: core.NewBasePlugin("postgres", 2002),
	}
}

func (p *PostgresPlugin) Init(cfg any) error {
	conf, ok := cfg.(*LhtSettings.PostgresConfig)
	if !ok {
		return errors.New("invalid config type: expected *PostgresConfig")
	}
	p.conf = *conf
	return nil
}

func (p *PostgresPlugin) Start() error {
	conf := p.conf
	if conf.SSLMode == "" {
		conf.SSLMode = "disable"
	}
	dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s",
		conf.Host, conf.Port, conf.User, conf.Password, conf.DbName)

	db, err := sql.Open("postgres", dsn)
	if err != nil {
		LhtLog.Error("PostgreSQL 连接失败", zap.Error(err))
		return err
	}
	if err = db.Ping(); err != nil {
		LhtLog.Error("PostgreSQL Ping 失败", zap.Error(err))
		return err
	}
	p.db = db

	LhtLog.Info("PostgreSQL 连接成功", zap.String("addr", conf.Host+":"+strconv.Itoa(conf.Port)))
	return p.BasePlugin.Start(p.handleData)
}

func (p *PostgresPlugin) handleData(data []byte) {
	fmt.Printf("[postgres] recv data: %s\n", string(data))
}

func (p *PostgresPlugin) Stop() error {
	if p.db != nil {
		return p.db.Close()
	}
	return nil
}
